﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Company.Merchandising.BusinessLayer.DataEntities;
using Company.Merchandising.DataAccessLayer.DataAccessCommon;
using Company.Merchandising.ServiceLayer.EntityManagement.Constants;
using Company.Merchandising.BusinessLayer.DataTransferObjects;

namespace Company.Merchandising.ServiceLayer.EntityManagement
{
	public class ProvinceManager : BaseManager
	{
		public ProvinceManager(MerchModelEntities modelEntities) : base(modelEntities) { }

		public void UpdateProvince(DTOProvince dtoProvince)
		{
			DACProvince dacProvince = new DACProvince(_modelEntities);
			if (dacProvince.GetProvincesByNameAndOtherId(dtoProvince.Name, dtoProvince.Id).Count() > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ProvinceAlreadyExist, dtoProvince.Name));
			}

			var foundProvince = dacProvince.GetProvinceById(dtoProvince.Id);
			if (foundProvince == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ProvinceDoesNotExistAnyMore, dtoProvince.Id));
			}

			foundProvince.Name = dtoProvince.Name;
			_modelEntities.SaveChanges();
		}

		public void AddProvince(DTOProvince dtoProvince)
		{
			DACProvince dacProvince = new DACProvince(_modelEntities);
			if (dacProvince.GetProvincesByName(dtoProvince.Name).Count() > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ProvinceAlreadyExist, dtoProvince.Name));
			}

			var newProvince = new Province();
			newProvince.Name = dtoProvince.Name;
			_modelEntities.AddObject(newProvince.GetType().Name, newProvince);
			_modelEntities.SaveChanges();
		}

		public void DeleteProvince(int provinceId)
		{
			DACProvince dacProvince = new DACProvince(_modelEntities);
			var foundProvince = dacProvince.GetProvinceById(provinceId);
			if (foundProvince == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ProvinceDoesNotExistAnyMore, provinceId));
			}

			if (!foundProvince.Cities.IsLoaded)
			{
				foundProvince.Cities.Load();
			}

			if (foundProvince.Cities.Count > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ProvincePossessesCities, provinceId));
			}

			_modelEntities.DeleteObject(foundProvince);
			_modelEntities.SaveChanges();
		}
	}
}
